// 实现这个项目的构建任务
const { src, dest, series, parallel, watch } = require("gulp");
const del = require("del");
const plugins = require("gulp-load-plugins")();

const browserSync = require("browser-sync");
const bs = browserSync.create();

const parseArgv = require("minimist");

const options = {
  alias: { e: "env" },
  string: ["env"],
  default: {
    env: "production",
  },
};
// 命令行参数
const cmdOptions = parseArgv(process.argv.slice(2), options);

// 编译模版
const page = () => {
  return src("src/*.html", { base: "src" })
    .pipe(plugins.swig())
    .pipe(dest("temp"));
};

// 处理scss
const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(
      plugins.sass({
        outputStyle: "expanded",
      })
    )
    .pipe(dest("temp"));
};

// 脚本
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("temp"));
};

// 图片
const image = () => {
  return src("src/assets/images/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

// 字体
const font = () => {
  return src("src/assets/fonts/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

const extra = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"));
};

const clean = () => {
  return del(["dist", "temp"]);
};

const serve = () => {
  watch("src/*.html", page);
  watch("src/assets/styles/*.scss", style);
  watch("src/assets/scripts/*.js", script);

  watch(
    ["src/assets/fonts/**", "src/assets/images/**", "public/**"],
    bs.reload
  );

  bs.init({
    notify: false,
    files: "temp/**",
    server: {
      baseDir: ["temp", "src", "public"],
      routes: {
        "/node_modules": "./node_modules",
      },
    },
  });
};

const useref = () => {
  return src("temp/*.html", { base: "dist" })
    .pipe(
      plugins.useref({
        searchPath: ["temp", "."],
      })
    )
    .pipe(plugins.if(/\.js/, plugins.uglify()))
    .pipe(plugins.if(/\.css/, plugins.cleanCss()))
    .pipe(
      plugins.if(
        /\.html/,
        plugins.htmlmin({
          minifyCSS: true,
          minifyJS: true,
        })
      )
    )
    .pipe(dest("dist"));
};

const compile = parallel(style, script, page);

const build = series(
  clean,
  parallel(series(compile, useref), image, font, extra)
);

// 开发
const develop = series(clean, parallel(compile, extra), serve);

// 发布
const deploy = (done) => {
  console.log(cmdOptions.env);
  done();
};

module.exports = {
  clean,
  serve: develop,
  build,
  start: develop,
  deploy,
};
